<template>
    <div>
        <div class="title-box">
            <custom-title title="我的钱包" />
        </div>
        <div class="container" ref="containerRef">
            <!-- 侧边账户列表 -->
            <el-scrollbar height="calc(100vh - 198px)">
                <div class="side app-container">
                    <div v-for="walletAccount in walletAccountList" @click="changeAccount(walletAccount)"
                        :class="{ 'account': true, active: currentAccountData.walletId == walletAccount.walletId }">
                        <el-tooltip class="box-item" effect="light" :content="walletAccount.memberName"
                            placement="top-start">
                            <div class="name">
                                {{ walletAccount.memberName }}
                            </div>
                        </el-tooltip>
                        <el-tag type="parimary" v-if="walletAccount.accountTypes?.length != 2"
                            v-for="item in (walletAccount.accountTypes || [])">
                            {{ accountTypes[item]?.title }}
                        </el-tag>
                        <el-tag v-if="walletAccount.memberStatus == 0">审核中</el-tag>
                        <template v-if="walletAccount.memberStatus != 0">
                            <div class="default" v-if="walletAccount.accountTypes?.length == 2">
                                {{ walletAccount.accountTypeName }}
                            </div>
                            <div class="set-default" v-else @click="openDefaultModel(walletAccount)">
                                设为默认
                            </div>
                        </template>
                    </div>
                    <el-affix position="bottom" :offset="40">
                        <div class="add-account" @click="addAccount(1)">
                            <el-icon>
                                <Plus />
                            </el-icon>新增账户
                        </div>
                    </el-affix>
                </div>
            </el-scrollbar>
            <!-- 右侧内容 -->
            <div class="content app-container" v-if="!isShowTagAndContent(currentAccountData.memberStatus)">
                <!-- 顶部卡片 -->
                <div class="card">
                    <div class="imgs">
                        <img src="../../assets/images/purse-left.png" alt="">
                        <img src="../../assets/images/purse-right.png" alt="">
                    </div>
                    <div class="info">
                        <div class="total">
                            <div class="title">总余额</div>
                            <div class="amount">¥{{
                                formattedAmount(currentAccountData.usableMoney - currentAccountData.freezeMoney)
                            }}</div>
                            <div class="countdown" v-if="Number(currentAccountData.freezeMoney) !== 0"><img
                                    src="@/assets/images/countdown.png" alt="">¥{{
                                        formattedAmount(currentAccountData.freezeMoney)
                                    }}提现中，预计发起后24小时到账</div>
                            <div class="operate-btn">
                                <div class="embodiment" @click="getPayoutsList">提现</div>
                                <div class="recharge" @click="openRechargeModal">充值</div>
                            </div>
                        </div>
                        <div>
                            <div class="amount">
                                <div class="title">本月收入</div>
                                <div>￥{{ formattedAmount(currentAccountData.monthlyIncome) }}</div>
                            </div>
                            <div class="amount">
                                <div class="title">本月支出</div>
                                <div>￥{{ Math.abs(currentAccountData.monthlyExpenditure) }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 右侧流水列表 -->
                <div class="details-title">
                    <div>交易记录</div>
                    <div class="is-link" @click="toMore">查看更多明细
                        <el-icon>
                            <DArrowRight />
                        </el-icon>
                    </div>
                </div>
                <el-scrollbar height="calc(100vh - 480px)" v-if="tradeDetailsList.length" @scroll="scroll">
                    <div>
                        <div class="item" v-for="tradeDetails in tradeDetailsList" :key="tradeDetails.walletRecordId">
                            <div>
                                <div class="name">{{ tradeDetails.memberName }}</div>
                                <div class="amount">{{ getAmount(tradeDetails.usableMoney) }}</div>
                            </div>
                            <div>
                                <div class="desc" :style="{ width: (width - 580) + 'px' }">
                                    {{ tradeDetails.remark || '--' }}
                                </div>
                                <div class="date">{{ tradeDetails.createTime }}</div>
                            </div>
                        </div>
                        <span ref="itemRef"></span>
                    </div>
                </el-scrollbar>
                <el-empty v-else />
                <div class="white" v-if="!gradient"></div>
            </div>
            <!-- 右侧特殊状态 -->
            <div class="audit-box" v-else>
                <template v-if="currentAccountData.memberStatus == 0">
                    <div>
                        <img src="@/assets/images/loading.png" alt=""></img>
                        <div class="text">正在审核中...</div>
                    </div>
                </template>
                <template v-else-if="currentAccountData.memberStatus == 1">
                    <div>
                        <img src="@/assets/images/success.png" alt=""></img>
                        <div class="text">审核通过</div>
                        <el-button type="primary" @click="addAccount(2)">绑定银行卡</el-button>
                    </div>
                </template>
                <template v-else-if="currentAccountData.memberStatus == 3">
                    <div>
                        <img src="@/assets/images/success.png" alt=""></img>
                        <div class="text">审核通过</div>
                        <el-button type="primary" @click="addAccount(3)">去签约</el-button>
                    </div>
                </template>
                <template v-if="currentAccountData.memberStatus == 2">
                    <div>
                        <img src="@/assets/images/error.png" alt=""></img>
                        <div class="text gray" :style="{ width: (width - 700) + 'px' }">
                            <div class="red">审核失败</div>
                            <div>
                                {{ currentAccountData.errorMessage }}
                            </div>
                        </div>
                        <div class="anew-submit-btn"><el-button type="primary" @click="anewSubmit">重新提交</el-button>
                        </div>
                    </div>
                </template>
                <el-Empty v-if="!walletAccountList.length" />
            </div>
        </div>
        <!-- 开通账户弹窗 -->
        <OpenAccount v-if="accountVisible" v-model="accountVisible" :retry="retry" :tenantId="tenantParams.tenantId"
            v-model:step="step" :currentAccountData="currentAccountData" @flushed="getWalletAccountListData"
            @openSure="openSure" />
        <!-- 提现弹窗 -->
        <Payouts v-if="payoutsVisible" v-model="payoutsVisible" :currentAccountData="currentAccountData"
            :bankCardList="bankCardList" @openBind="openBind" @bankCardshow="bankCardshow" />
        <!-- 绑定弹窗 -->
        <Bind v-if="bindVisible" v-model="bindVisible" :currentAccountData="currentAccountData" :bankCardNum="bankCardList.length" @getList="getPayoutsList" />
        <Recharge v-model="rechargeVisible" :currentAccountData="currentAccountData" @flushed="getWalletAccountListData"/>
        <el-dialog v-model="sureVisible" width="400" center align-center :show-close="false">
            <div class="sure">
                <div>
                    <el-icon>
                        <Warning />
                    </el-icon>
                </div>
                <span>是否已在对应链接完成签约？</span>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="sureVisible = false">否</el-button>
                    <el-button type="primary" @click="comfrimSignCallback">是</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="defaultVisible" width="400" center align-center :show-close="false">
            <template #header>
                <custom-title title="设置默认" />
            </template>
            <el-checkbox-group v-model="setDefaultParams.accountTypes">
                <el-checkbox v-for="item, index in accountTypes" :value="index"
                    :label="`${item.title}-${item.desc}`"></el-checkbox>
            </el-checkbox-group>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="defaultVisible = false">取消</el-button>
                    <el-button type="primary" @click="setDefault">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted,watch } from "vue";
import { useElementBounding, useIntersectionObserver } from '@vueuse/core';
import OpenAccount from "./components/OpenAccount/index.vue";
import Payouts from "./components/Payouts/index.vue";
import { formattedAmount } from "@/utils";
import { tenantParams } from "@/utils/config";
import Bind from "./components/Bind/index.vue";
import { useRouter } from "vue-router";
import { getWalletAccountList, getTradeList, setDefaultAccount, getWithdrawAccountList } from "@/apis/purse";
import { getMemberDetail } from "@/apis/purse/member";
import { ElMessage } from "element-plus";
import Recharge from "./components/Recharge";

const router = useRouter();
const itemRef = ref()
const containerRef = ref(null);
const { width } = useElementBounding(containerRef);
const accountVisible = ref(false);// 开户弹窗
const payoutsVisible = ref(false);// 提现弹窗
const bindVisible = ref(false);// 绑定弹窗
const walletAccountList = ref([]);// 左侧账户列表
const tradeDetailsList = ref([]); // 支付流水列表
const currentAccountData = ref({});// 当前选中的账户数据
const bankIsAdd = ref(false);// 当前是否是新增银行卡
const sureVisible = ref(false)
const rechargeVisible = ref(false);
const retry=ref(false)
const accountTypes = {
    'RECEIVING': { title: '收单', desc: '对方在付款给我方时，看到的账户' },
    'WITHDRAWAL': { title: '提现', desc: '收款佣金、退款时实际提现的到账账户' }
}
/**
 * 切换左侧账户选中样式and数据
 */
const changeAccount = (item) => {
    currentAccountData.value = item;
    getTradeDetailsListData()
}
const gradient = ref(false);// 流水底部渐变
/**
 * 滚动流水列表
 */
const scroll = () => {
    useIntersectionObserver(
        itemRef,
        ([{ isIntersecting }]) => {
            gradient.value = isIntersecting
        }
    )
}
/**
 * 当前账户是否显示标签and内容
 */
const isShowTagAndContent = (memberStatus) => {
    if ([null, undefined].includes(memberStatus)) return true;
    return [0, 1, 2, 3].includes(memberStatus);
}
const openSure = () => {
    sureVisible.value = true
}
/**
 * 当前提现账户银行卡列表
 */
const bankCardList = ref([]);
/**
 * 切换银行卡脱敏
 */
const bankCardshow = (item) => {
    item.desensitization = !item.desensitization;
}
/**
 * 查询提现账户列表
 */
const getPayoutsList = async () => {
    try {
        const res = await getWithdrawAccountList({ walletId: currentAccountData.value.walletId });
        bankCardList.value = res.data ? res.data.map(v => ({ ...v, desensitization: true })) : [];
        payoutsVisible.value = true;
    } catch (error) {

    }
}
/**
 * 打开充值弹窗
 */
const openRechargeModal = () => {
    rechargeVisible.value = true;
}
const step = ref(1);
/**
 * 新建账户
 */
const addAccount = (current) => {
    step.value = current;
    accountVisible.value = true;
}
/**
 * 打开绑定弹窗
 */
const openBind = (add) => {
    bindVisible.value = true;
    bankIsAdd.value = add;
}
/**
 * 携带当前钱包id跳转流水页面
 */
const toMore = () => {
    router.push(`/finance/tradedetails?walletId=${currentAccountData.value.walletId}`)
}
/**
 * 重新提交
 */
const anewSubmit = async () => {
    try {
        const res = await getMemberDetail({ walletId: currentAccountData.value.walletId });
        currentAccountData.value.companyInfo = res.data.companyInfo;
        retry.value=true;
        addAccount(1)
    } catch (error) {

    }
}
/**
 * 获取左侧账户列表
 */
const getWalletAccountListData = async (callbak) => {
    try {
        const res = await getWalletAccountList(tenantParams);
        walletAccountList.value = res.data || [];
        if (callbak) currentAccountData.value = callbak(walletAccountList.value);
        else if (walletAccountList.value.length) {
            currentAccountData.value = walletAccountList.value[0];
        }
        if (walletAccountList.value.length) getTradeDetailsListData();
        sureVisible.value = false;
    } catch (error) {
        console.log(error)
    }
}
watch(()=>accountVisible.value,(newV)=>{
    if(!newV)retry.value=false;
})
const comfrimSignCallback = () => {
    sureVisible.value = false;
    getWalletAccountListData()
}
/**
 * 获取支付流水列表
 */
const getTradeDetailsListData = async () => {
    try {
        // 待补充参数
        const params = {
            walletId: currentAccountData.value.walletId,
            current: 1,
            size: 10,
            ...tenantParams
        }
        const res = await getTradeList(params);
        tradeDetailsList.value = res.data.list || [];
    } catch (error) {
        console.log(error)
    }
}
const defaultVisible = ref(false);
const setDefaultParams = ref({})
const openDefaultModel = (item) => {
    const accountTypes = item.accountTypes ? item.accountTypes : []
    setDefaultParams.value = { ...item, accountTypes }
    defaultVisible.value = true
}
/**
 * 设置账户默认
 */
const setDefault = async () => {
    if (!setDefaultParams.value.accountTypes.length) return ElMessage.error('默认规则不能为空')
    try {
        const params = {
            accountId: setDefaultParams.value.memberId,
            ...tenantParams,
            accountType: setDefaultParams.value.accountTypes,
        }
        await setDefaultAccount(params);
        ElMessage.success('设置成功')
        getWalletAccountListData();
        defaultVisible.value = false;
    } catch (error) {
        console.log(error)
    }
}

/**
 * 根据流水金额，返回带符号的绝对值
 * @param {*} amount 金额：正负值
 */
const getAmount = (amount) => {
    return (amount >= 0 ? '+￥' : '-￥') + formattedAmount(Math.abs(amount))
}
onMounted(() => {
    getWalletAccountListData()
})
</script>

<style lang="scss" scoped>
::v-deep(.el-scrollbar) {
    height: unset !important;
}

.title-box {
    height: 64px;
    padding: 20px;
    border-bottom: $border;
    box-sizing: border-box;
}

.container {
    @include mixin.flex;
    height: calc(100vh - 198px);

    >div {
        height: 100%;
    }

    .side {
        width: 300px;
        box-sizing: border-box;
        padding-bottom: 20px;
        min-height: calc(100vh - 198px);
        background: #F4F5F7;

        [class*=account] {
            margin-bottom: 20px;
            padding: 20px;
            box-shadow: 0px 0px 10px 0px rgba(134, 144, 156, 0.1);
            border-radius: 10px;
            height: 50px;
            background: white;
            box-sizing: border-box;
            border: 2px solid white;
        }

        .account {
            @include mixin.flex-center(space-between, center);

            [class*=default] {
                width: 64px;
                height: 24px;
                text-align: center;
                line-height: 24px;
                border-radius: 2px;
                font-size: 12px;
            }

            .default {
                background: #FFFFFF;
                border: 1px solid #86909C;
                color: #86909C;
            }

            .set-default {
                background: #007DFF;
                border: 1px solid #007DFF;
                color: white;
                cursor: pointer;
            }

            .name {
                width: 38%;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                cursor: pointer;
            }
        }

        .add-account {
            @include mixin.flex-center;
            gap: 10px;
            color: $topic;
            cursor: pointer;
            user-select: none;
        }

        .active {
            border: 2px solid $topic;
        }
    }



    .content {
        flex: 1;
        position: relative;

        .card {
            height: 192px;
            background: #0080BE;
            border-radius: 9px;
            position: relative;
            overflow: hidden;

            .imgs {
                height: 100%;
                @include mixin.flex-center(space-between, end);

                img {
                    height: 100%;

                    &:last-child {
                        height: 90%;
                    }
                }

            }

            .info {
                width: 100%;
                position: absolute;
                top: 0;
                height: 100%;
                color: white;
                @include mixin.flex;

                .total {
                    width: 440px;
                    height: 100%;
                    border-right: 1px solid #329CCF;
                    padding: 17px 50px;
                    box-sizing: border-box;
                    display: grid;
                    grid-template-columns: 1fr;

                    >div {
                        @include mixin.flex-align;
                    }

                    .title {
                        font-size: 16px;
                        font-weight: 500;
                    }

                    .amount {
                        font-size: 50px;
                        font-family: Lato;
                        font-weight: bold;
                    }

                    .countdown {
                        display: flex;
                        gap: 6px;
                        align-items: center;
                        color: rgba(255, 255, 255, 0.7);
                        font-size: 12px;

                        img {
                            height: 16px;
                            width: 16px;
                        }
                    }

                    .operate-btn {
                        display: flex;
                        gap: 10px;

                        >div {
                            @include mixin.flex-center;
                            cursor: pointer;
                            user-select: none;
                        }
                    }

                    .embodiment {
                        width: 78px;
                        height: 34px;
                        background: #FFBE12;
                        border-radius: 2px;
                        color: white;
                        @include mixin.flex-center;
                        cursor: pointer;
                        user-select: none;
                    }

                    .recharge {
                        width: 76px;
                        height: 32px;
                        background: rgba(255, 255, 255, 0.4);
                        border-radius: 2px 2px 2px 2px;
                        border: 1px solid #FFFFFF;
                    }
                }

                >div:last-child {
                    flex: 1;

                    .amount {
                        font-size: 32px;
                        font-family: Lato;
                        font-weight: 300;
                        width: 100%;
                        height: 50%;
                        padding: 17px;
                        box-sizing: border-box;
                        display: grid;
                        grid-template-columns: 1fr;

                        >div {
                            @include mixin.flex-align;
                        }

                        .title {
                            font-size: 14px;
                        }

                    }

                    .amount:first-child {
                        border-bottom: 1px solid #329CCF;
                    }
                }
            }
        }

        .details-title {
            @include mixin.flex-center(space-between, center);
            margin-top: 29px;

            .is-link {
                @include mixin.flex-align;
                gap: 6px;
            }
        }

        .item {
            height: 87px;
            display: grid;
            grid-template-columns: 1fr;
            padding: 10px 0;
            box-sizing: border-box;
            border-top: $border;

            >div {
                @include mixin.flex-center(space-between, center);

            }

            &:first-child {
                border-top: none;
            }

            >div:first-child {
                font-weight: bold;
                border-top: none;
            }

            .amount {
                color: #FF3333;
            }

            .date {
                color: #86909C;
                font-size: 12px;
            }

            .desc {
                color: #606266;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

        }

        .white {
            height: 80px;
            width: 100%;
            position: absolute;
            bottom: 40px;
            right: 0;
            background: linear-gradient(rgba(255, 255, 255, 0.5), white);
        }
    }

    .audit-box {
        width: calc(100% - 300px);
        height: calc(100vh - 300px);
        @include mixin.flex-center;

        img {
            width: 130px;
            display: block;
            margin: 0 auto;
        }

        .text {
            width: 100%;
            text-align: center;
            color: #86909C;
        }

        .gray {
            background: #F2F3F5;
            border-radius: 4px;
            padding: 20px;
            line-height: 22px;
            text-align: left;

            .red {
                color: #FF3333;
            }
        }

        >div {
            ::v-deep(.el-button) {
                display: block;
                margin: 10px auto;
            }
        }
    }


    .anew-submit-btn {
        @include mixin.flex-center;
    }
}
</style>